#!/usr/bin/env python
'''
Created on Dec 7, 2010

@author: brendenjeon
'''

import time
import subprocess
import urllib, urllib2
from datetime import datetime, date
import re
import os
import logging

def get_weather(cities={'seoul':'1132599', 'brisbane':'1100661'}): #seoul, brisbane
    info = {}
    for city in cities.keys():
        url = 'http://weather.yahooapis.com/forecastrss?w=' +\
            urllib2.quote(cities[city]) + '&u=c'
        try:
            f = urllib2.urlopen(url)
            weather = f.read().split('<yweather:condition  text=\"')[-1].split('\"')[0]
            if weather == '<?xml version=':
                weather = 'Invalid city'
            info[city] = weather
        except:
            return False
    return info

def ping(hostname='www.vsix.kr'):
    if os.name not in ['nt', 'posix']:
        return False
    info = {}
    losses_pattern_str = ''
    speend_pattern_str = ''
    option = ''

    if os.name == 'nt':
        losses_pattern_str = r'([0-9.]+)% loss'
        speend_pattern_str = r'Minimum = ([0-9.]+)ms, Maximum = ([0-9.]+)ms, Average = ([0-9.]+)ms'
        option = '-n'
    else:
        losses_pattern_str = r'([0-9.]+)%'
        speend_pattern_str = r'([0-9.]+)/([0-9.]+)/([0-9.]+)/([0-9.]+)'
        option = '-c'
    
    ping = subprocess.Popen(['ping', option, '5', hostname],
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE
        )

    out, error = ping.communicate()
#    print out

    try:
        losses_pattern = re.compile(losses_pattern_str)
        speed_pattern = re.compile(speend_pattern_str)
        info['loss'] = losses_pattern.search(out).groups()[0]
        info['min'] = speed_pattern.search(out).groups()[0]
        if os.name == 'nt':
            info['avg'] = speed_pattern.search(out).groups()[2]
            info['max'] = speed_pattern.search(out).groups()[1]
        else:
            info['avg'] = speed_pattern.search(out).groups()[1]
            info['max'] = speed_pattern.search(out).groups()[2]
    except:
        info['loss'] = '0.0'
        info['min'] = '0.0'
        info['avg'] = '0.0'
        info['max'] = '0.0'
        print 'No connected to the internet'
    finally:
        info['date'] = datetime.now()

    return info

def is_checking_time():
    today = date.today()
    checking_start_time = datetime(today.year, today.month, today.day, 9, 00)
    checking_end_time = datetime(today.year, today.month, today.day, 22, 00)
    now = datetime.now()
    print 'checking time'
    print now
    if checking_start_time < now and now < checking_end_time:
        print 'true'
        return True
    else:
        print 'false'
        return False

def set_info():
    info = ping()
    winfo = get_weather()
    info.update(winfo)
    print 'after weather'
    print info
    return info

def send_database(info_queue):
    retry_info_queue = []
    for info in info_queue:
        params = urllib.urlencode(info)
        url = 'http://iuc-schedule.appspot.com/iuc/internet/'
        try:
            request = urllib2.Request(url, params)
            response = urllib2.urlopen(request)
            print 'send end'
        except:
            retry_info_queue.append(info)
            print 'Save info. No connected to the internet'
    return retry_info_queue

def monitering():
    info_queue = []
    while 1:
        if is_checking_time():
            info = set_info()
            info_queue.append(info)
            info_queue = send_database(info_queue)
            time.sleep(60 * 30) #30min

if __name__ == '__main__':
    #monitering()
    d = ping('202.126.104.188')
    print d
